<?php


namespace App\backend\controllers;

use App\backend\services\AdminUsersServices;
use App\backend\services\LoginLogServices;
use App\backend\services\AdminLoginLogServices;
use App\backend\services\AdminUsersServices;
use Illuminate\Support\Facades\Validator;
use App\Utils\JsonResp;

class LogonController
{

    /**
     * 总后台——登录
     */
    public function adminLogon()
    {
        $req_data = file_get_contents( "php://input");
        $data = $req_data?json_decode($req_data,true):'';
        if (!$data){
            return JsonResp::error('非法操作');
        }

        $validator = Validator::make($data,
            [
                'username' => 'required',
                'password' => 'required|min:6',
            ],
            [
                'username.required' => '请输入账号',
                'password.required' => '请输入密码',
                'password.min' => '密码最小长度为6',
            ]);


        if ($validator->fails()){
            return JsonResp::error($validator->errors()->first());
        }

        $username = $data['username'];
        $password = $data['password'];
        if (preg_match('/[\x{4e00}-\x{9fa5}]/u', $password)>0) {
            return JsonResp::error(['密码不能含有中文']);
        }

        // 账号密码
        $user_data = ['username'=>$username,'password'=>$password];
        //进行auth验证
        $adminUserToken = auth('backend')->attempt($user_data);
        if (!$adminUserToken){
            return JsonResp::error('用户名或密码错误');
        }

        $token = 'Bearer ' . $adminUserToken;
        $user_id = auth('backend')->id();
        $login_ip = get_client_ip_info();
        $login_time = time();
        AdminUsersServices::updateLoginData($login_ip, $user_id, $token, $login_time);
        AdminLoginLogServices::insertLoginData($login_ip, $login_time);
        return JsonResp::success('登录成功',['token'=>$token]);
    }

}
